/* eslint-disable */
<template>
	<!-- 新增，删除，延期，预申请角色权限 -->
	<div v-if="show">
		<el-dialog class="handleDialog" :title="title" :visible.sync="show"   width="60%"  :close-on-click-modal="false"  @close="closeDiolag">
			<el-row>
			    <el-form :rules="rules"  :inline="false"  :model="dataEmpForm" ref="dataEmpForm" label-width="110px">
	                <p><span style="font-weight:bold;">{{$t('components.handleResource.step1')}}：</span>{{$t('components.handleResource.selectByAccountTip')}}</p>
	                <el-row>
	                    <el-col :span="12">
	                        <el-form-item :label="$t('common.byUserName')+':'" prop="userName">
	                        	<el-select v-model="dataEmpForm.userName" filterable :placeholder="$t('common.selectPlaceholder')"   :filter-method="byAccountOptionsFun">
								    <el-option  @click.native="handleSelectByForm(item)"
								      v-for="item in byAccountOptions" :key="item.code" :label="item.label"  :value="item.code">
								    </el-option>
								</el-select>
						    </el-form-item>
	                    </el-col>
	                    <el-col :span="12">
	                        <el-form-item :label="$t('common.empName')+':'" prop="empName">
	                        	<el-input disabled v-model="dataEmpForm.empName" :placeholder="$t('common.inputPlaceholder')"></el-input>
						    </el-form-item>
	                    </el-col>
	                    <el-col :span="12">
	                        <el-form-item :label="$t('common.positionName')+':'" prop="positionName">
	                        	<el-input disabled v-model="dataEmpForm.positionName" :placeholder="$t('common.inputPlaceholder')"></el-input>
						    </el-form-item>
	                    </el-col>
	                     <el-col :span="12">
	                        <el-form-item :label="$t('common.orgName')+':'" prop="orgName">
	                        	<el-input disabled v-model="dataEmpForm.orgName" :placeholder="$t('common.inputPlaceholder')"></el-input>
						    </el-form-item>
	                    </el-col>
	                </el-row>
	            </el-form>
	            <el-form :rules="isSwitchRole=='1'?rules:rules2"  :inline="false"  :model="dataSourceForm" ref="dataSourceForm" label-width="110px">
	                <p><span style="font-weight:bold;">{{$t('components.handleResource.step2')}}：</span>{{$t('components.handleResource.selectGatagroup')}}</p>
	                <el-row>
	                	<el-col :span="8" v-show="isSwitchRole=='1'">
							<el-form-item :label="$t('common.subsysName')+':'" prop="subsysName">
								<el-select  v-model="dataSourceForm.subsysName" :placeholder="$t('common.selectPlaceholder')" >
									<el-option  @click.native="handleSelectSubsys(item)" v-for="(item,index) in subsysTemOptions" :key="index" :label="item.label" :value="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8" v-show="isSwitchRole=='1'">
							<el-form-item :label="$t('common.roleName')+':'" prop="roleName" >
								<el-select  v-model="dataSourceForm.roleName" :placeholder="$t('common.selectPlaceholder')" clearable :filter-method="getroleList">
									<el-option  @click.native="dataSourceForm.resourceName='';dataSourceForm.resourceId='';resourceOptionsFun('')"  v-for="(item,index) in roleNameOptions" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8" >
		                  	<el-form-item :label="$t('common.resourceName')+':'" prop="resourceName" >
			  					 <el-select v-model="dataSourceForm.resourceName" filterable :placeholder="$t('common.selectPlaceholder')"   :filter-method="resourceOptionsFun">
								    <el-option @click.native="handleSelectResource(item)"
								      v-for="item in resourceOptions"
								      :key="item.id"
								      :label="item.label"
								      :value="item.label">
								    </el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24"  v-show="isSwitchRole=='1'">
							<el-col :span="8">
								<el-form-item :label="$t('common.dataGroupName')+':'"  >
									<el-input  v-model="dataSourceForm.dataGroupName" :placeholder="$t('common.inputPlaceholder')"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8" style="padding-left: 15px;">
								<el-button  type="primary" @click="searchDataList" >{{$t('common.searchBtn')}}</el-button>
								<el-button   @click="reset" >{{$t('common.resetBtn')}}</el-button>
							</el-col>
						</el-col>
						<el-col :span="8" v-show="isSwitchRole!='1'">
								<el-form-item  :label="$t('common.dataGroupName')+':'" >
									<el-input  v-model="dataSourceForm.dataGroupName" :placeholder="$t('common.inputPlaceholder')"></el-input>
								</el-form-item>
							</el-col>
						<el-col v-if="isSwitchRole!='1'" :span="6" style="padding-left: 15px;">
							<el-button  type="primary" @click="searchDataList" >{{$t('common.searchBtn')}}</el-button>
							<el-button   @click="reset" >{{$t('common.resetBtn')}}</el-button>
						</el-col>

					</el-row>
					<el-row>
						<el-col :span="24">
							<el-table v-loading="loadind1"  ref="datatableList" :data="datatableList" border max-height="500"  style="width: 100%" @selection-change="selectAddListChange" >
					  		 	<el-table-column :selectable="selectableFun"   type="selection" width="55"></el-table-column>
					  		 	 <el-table-column prop="ruleType" :label="$t('common.ruleType')"   show-overflow-tooltip></el-table-column>
							    <el-table-column prop="resourceName" :label="$t('common.resourceName')"  show-overflow-tooltip> </el-table-column>
							    <el-table-column prop="dataGroupName" :label="$t('common.dataGroupName')"  show-overflow-tooltip >  </el-table-column>
							    <el-table-column prop="isCustom" :label="$t('common.isCustom')" show-overflow-tooltip :formatter="formatter">  </el-table-column>
							</el-table>
							<div style="position: relative;">
								<span v-if="dataSourceForm.customDatagroup!==0  && dataSourceForm.ownerSysId==dataSourceForm.systemId" style="position: absolute;"> {{$t('components.handleResource.bythisWay')}}<el-button style="margin:0 10px;" size="small" type="primary" @click="autoDefined">{{$t('components.handleResource.autoDefined')}}</el-button>{{$t('components.handleResource.createOrEditAutodefined')}}</span>
								<el-pagination
							      @size-change="pageSizeChange1"
							      @current-change="handleCurrentChangePage1"
							      :current-page="pagination1.currentPage"
							      :page-sizes="[10,20, 50, 100, 200]"
							      :page-size="pagination1.pageSize"
							      layout="->,prev, pager, next, sizes,total"
							      :pager-count="5"
							      :total="pagination1.totalSize">
							    </el-pagination>
							</div>
						</el-col>
	                </el-row>
	                <br>
	                <p ><span style="font-weight:bold;">{{$t('components.handleResource.step3')}}：</span>{{$t('components.handleResource.maintainValidate')}}</p>
	                <el-row >
	                    <el-col :span="24" >
	                        <el-form-item :label="$t('common.startTm')+':'" class="is-required" :class="(showError && !dataSourceForm.startTm)?'is-error':''">
	                        	<el-date-picker @change="checkDateValid('startTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd"    v-model="dataSourceForm.startTm"  type="date"  :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleResource.completionStartTime')}}）</span>
						    	<div class="el-form-item__error" v-if="showError && !dataSourceForm.startTm">
						        	{{$t('validateWornText.slectStartTm')}}
						        </div>
	                        </el-form-item>
	                    </el-col>
	                     <el-col :span="24">
	                        <el-form-item :label="$t('common.endTm')+':'" class="is-required" :class="(showError && !dataSourceForm.endTm)?'is-error':''">
	                        	<el-date-picker @change="checkDateValid('endTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd"    v-model="dataSourceForm.endTm"  type="date"  :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleResource.completionEndTime')}}）</span>
						    	<div class="el-form-item__error" v-if="showError && !dataSourceForm.endTm">
						        	{{$t('validateWornText.slectEndTm')}}
						        </div>
	                        </el-form-item>
	                    </el-col>
	                </el-row>
	            </el-form>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button @click="$emit('exit') ">{{$t('common.giveUp')}}</el-button>
				<el-button type="primary" @click="save">{{$t('common.save')}}</el-button>
			</div>
		</el-dialog>
		<custom-datagroup :visible="autoDefinedVisible" @customDialogClose="customDialogClose" @customDialogSave="customDialogSave"  :formInfo="dataSourceForm" ></custom-datagroup>
	</div>

	<!-- 新增，删除，延期，预申请角色权限 -->
</template>

<script>
import customDatagroup from './customDatagroup'
import {
    Message, Notification, MessageBox, Loading
} from 'element-ui'
export default {
    name: 'handleResource',
    props: [
        'visible'
    ],
    components: {
        customDatagroup
    },
    data () {
        return {
            show: false,
            dataEmpForm: {
                userName: '',
                empName: '',
                positionName: '',
                orgName: '',
                byAccountId: ''
            },
            dataSourceForm: {
                systemName: '',
                systemId: '',
                subsysName: '',
                roleName: '',
                endTm: '',
                startTm: '',
                resourceName: '',
                dataGroupName: ''
            },
            pickerOptions1: {
                disabledDate (time) {
		            return (time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000)
		        }
            },
            rules: {
                userName: [
		            { required: true, message: this.$t('validateWornText.selectByAccount'), trigger: 'change' }
		        ],
		        subsysName: [
		            { required: true, message: this.$t('validateWornText.selectSubsysName'), trigger: 'change' }
		        ],
		        resourceName: [
		            { required: true, message: this.$t('validateWornText.selectResourceName'), trigger: 'change' }
		        ],
		        roleName: [
		            { required: true, message: this.$t('validateWornText.selectRoleName'), trigger: 'change' }
		        ]
            },
            rules2: {
                userName: [
		            { required: true, message: this.$t('validateWornText.selectByAccount'), trigger: 'change' }
		        ],
		        resourceName: [
		            { required: true, message: this.$t('validateWornText.selectResourceName'), trigger: 'change' }
		        ]
            },
            roleNameOptions: [],
            subsysTemOptions: [],
            byAccountOptions: [],
            datatableList: [],
            resourceOptions: [],
            pagination1: {
                totalSize: 0,
                pageSize: 10,
                currentPage: 1,
                totalPage: 0
            },
            title: '',
            loadind1: false,
            addSelectMultipleSelection: [],
            showError: false,
            autoDefinedVisible: false,
            systemInfo: {},
            isSwitchRole: ''
        }
    },
    watch: {
        visible: 'visibleChange'
    },
    mounted () {
    	this.searchSystemInfo()
    },
    methods: {
    	async searchSystemInfo(){
    		this.systemInfo = this.$getSystemInfo()
        	this.isSwitchRole = this.systemInfo.isSwitchRole
    	},
        visibleChange (val) {
            this.show = val
            if (val) {
                this.getSubSystemList()
                this.byAccountOptionsFun('')
                this.resourceOptionsFun('')
                this.title = this.$t('components.handleResource.assigndataGroup')
            } else {
                this.closeDiolag()
            }
        },
        checkDateValid (param) {
            this.showError = !((this.dataSourceForm.startTm && this.dataSourceForm.endTm))
            if (this.dataSourceForm.startTm != '' && this.dataSourceForm.endTm != '') {
                if (this.dataSourceForm.startTm > this.dataSourceForm.endTm) {
                    this.$message({
				          message: this.$t('common.conmareEndTimeTip'),
				          type: 'warning'
				    })
                    this.dataSourceForm[param] = ''
                }
            }
        },
        clear () {
            this.$refs['dataSourceForm'].resetFields()// 重置表单
            this.dataSourceForm = {
                systemName: '',
                systemId: '',
                subsysName: '',
                roleName: '',
                endTm: '',
                startTm: '',
                resourceName: '',
                dataGroupName: ''
            }
            this.pagination1.currentPage = 1
            this.datatableList = []
            this.addSelectMultipleSelection = []
            this.roleNameOptions = []
            this.showError = false
        },
        reset () { // 重置模态框数据
            this.$refs['dataEmpForm'].resetFields()// 重置表单
            this.dataEmpForm = {
                userName: '',
                empName: '',
                positionName: '',
                orgName: '',
                byAccountId: ''
            },
            this.clear()
	    },
	    async resourceOptionsFun (queryString) { // 资源名称模糊搜索
            this.resourceOptions = await this.$resourceOptionsFun(queryString, this.dataSourceForm.roleName)
        },
        handleSelectResource (item) { // 选择资源后
            this.dataSourceForm.ownerSysId = item.ownerSysId
            this.dataSourceForm.resourceId = item.id
            this.dataSourceForm.customDatagroup = item.customDatagroup
            this.dataSourceForm.systemId = item.systemId
            this.dataSourceForm.paramStruct = item.paramStruct
	    	this.dataSourceForm.paramUrl=item.paramUrl
	    	this.dataSourceForm.paramType=item.paramType
            this.dataSourceForm.dataGroupName = ''
            this.pagination1.currentPage = 1
            this.datatableList = []
            this.addSelectMultipleSelection = []
            // this.dataGroupNameOptionsFun('')
        },
        /* 搜索百源账号 */
        async byAccountOptionsFun (queryString) {
            this.byAccountOptions = await this.$byAccountOptionsFun(queryString)
        },
        handleSelectByForm (item) {
            this.dataEmpForm.byAccountId = item.id
            this.searchEmpInfo(item.code)
            this.pagination1.totalSize = 0
            this.pagination1.currentPage = 1
            this.datatableList = []
            this.dataSourceForm.subsysName = ''
            this.dataSourceForm.resourceName = ''
            this.dataSourceForm.resourceId = ''
        },
        searchEmpInfo (code) { // 根据百源账号id查员工信息
            var urlH = '/dev-basp-user/sysAccount/queryUserInfo/' + code
            this.$httpExt().get(urlH)
                .then((response) => {
                    var body = response.result
                    this.dataEmpForm.empName = body.empName
                    this.dataEmpForm.positionName = body.positionName
                    this.dataEmpForm.orgName = body.orgName
                }, (response) => {
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
        },
        /**
		 * @author：xmj
		 * @function:获取子系统列表
		 */
        async getSubSystemList (val) {
            this.subsysTemOptions = await this.$getSubSystemList(val)
        },
        handleSelectSubsys (item) { // 选择子系统时查角色
            this.pagination1.currentPage = 1
            this.datatableList = []
            this.addSelectMultipleSelection = []
            this.dataSourceForm.subsysCode = item.value
            this.dataSourceForm.roleName = ''
            this.getroleList('')
        },
        async getroleList (val) { // 根据子系统编码查角色
            if (!this.dataEmpForm.byAccountId) {
                return
            }
            this.roleNameOptions = await this.$getroleListFun(val, this.dataSourceForm.subsysCode, this.dataEmpForm.byAccountId)
        },
        selectAddListChange (val) { // 数据组列表勾选
            this.addSelectMultipleSelection = val
        },
        searchDataList () { // 查询角色列表
	    	this.$refs['dataSourceForm'].validate((valid) => {
			    if (valid) {
			    	this.searchDataListList()
			    	// 根据子系统编号搜索角色
			    } else {
			    	return false
                }
            })
	    },
	    searchDataListList () {
	    	var param = {
                pageSize: this.pagination1.pageSize,
                pageNum: this.pagination1.currentPage,
                byAccountId: this.dataEmpForm.byAccountId,
                resourceId: this.dataSourceForm.resourceId,
                dataGroupName: this.dataSourceForm.dataGroupName
            }
	    	var urlH = '/dev-basp-user/accountDataGroup/queryAllRuleDataGroup'
            this.loadind1 = true
            this.$httpExt().post(urlH, param)
                .then((response) => {
                    this.loadind1 = false
                    var body = response.result
                    this.datatableList = body.data
                    this.pagination1.totalSize = body.totalSize
                }, (response) => {
                    this.loadind1 = false
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
	    },
		 // 搜索角色权限列表清单
	    handleCurrentChangePage1 (val) { // 角色列表分页
            this.pagination1.currentPage = val
            this.searchDataList()
        },
        pageSizeChange1 (val) { // 角色列表分页
            this.pagination1.currentPage = 1
            this.pagination1.pageSize = val
            this.searchDataList()
        },
        save () {
            var that = this
	    	this.$refs['dataSourceForm'].validate((valid) => {
			    if (valid) {
			    	if (!that.dataSourceForm.endTm || !that.dataSourceForm.startTm) { // 未填写生效或者失效时间
			    		that.showError = true
			    	} else if (that.addSelectMultipleSelection.length < 1) { // 未勾选角色
			    		MessageBox({
                            message: this.$t('common.emptyTip'),
                            confirmButtonText: this.$t('common.iknow')
                        })
			    	} else { // 页面值校验通过
			    		var obj = Object.assign(that.dataSourceForm, this.dataEmpForm)
			    		that.$emit('dataHandleSave', obj, that.addSelectMultipleSelection)
			    	}
			    } else {
			    	if (!that.dataSourceForm.endTm || !that.dataSourceForm.startTm) { // 未填写失效时间
			    		that.showError = true
			    	}
			    	return false
                }
            })
        },
        autoDefined () { // 自定义按钮
            this.$refs['dataSourceForm'].validate((valid) => { // 根据当前条件查询自定义数据组若无则需要新建
	    		if (valid) {
	    			var urlH = '/dev-basp-user/accountDataGroup/selectCustomDateGroup'
	    			var param = {
	    				resourceId: this.dataSourceForm.resourceId,
	    				resourceName: this.dataSourceForm.resourceName,
	    				username: this.dataEmpForm.userName,
	    				byAccountId: this.dataEmpForm.byAccountId
	    			}
                    this.$httpExt().post(urlH, param)
                        .then((response) => {
                            this.dataSourceForm.dataGroupId = response.result.dataGroupId
                            this.dataSourceForm.dataGroupName = response.result.dataGroupName
                            this.autoDefinedVisible = true
                        }, (response) => {
                            Notification.error({
                                title: this.$t('common.exception'),
                                message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                            })
                        })
			    } else {
			    	return false
                }
            })
        },
        selectableFun (value, row, column) {
            /* return value.ruleType=='C'?false:true */
            return true
        },
        closeDiolag () {
            this.reset()
            this.$emit('close')
        },
        // 自定义数据组相关操作
        customDialogClose () { // 关闭自定义数据组弹框
            this.autoDefinedVisible = false
        },
        customDialogSave (dataSourceRow, currentCheckedNodes) { // 创建了自定义数据组后保存
            this.saveResourceChecked(dataSourceRow, currentCheckedNodes)
        },
        saveResourceChecked (dataSourceRow, currentCheckedNodes) { // 提交该自定义数据组的勾选
	    	var codeList = []
    		for (var i = 0; i < currentCheckedNodes.length; i++) {
    			codeList.push(currentCheckedNodes[i].code)
    		}
    		var param = {
                dataGroupId: dataSourceRow.dataGroupId,
                resourceId: dataSourceRow.resourceId,
                codeList: codeList
            }
	    	var urlH = "/dev-basp-user/accountDataGroup/saveCustomParams"
            let loadingInstance = Loading.service({ fullscreen: true })
            this.$httpExt().post(urlH, param)
                .then((response) => {
                    loadingInstance.close()
                    this.$message({
			          message: response.msg ? response.msg : this.$t('components.handleResource.appendSuccess'),
			          type: 'success'
			    })
			    this.autoDefinedVisible = false
			    this.appendDataGroupToAccount(dataSourceRow)
                }, (response) => {
                    loadingInstance.close()
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
	    },
	    appendDataGroupToAccount (dataSourceRow) { // 重新搜索数据组
	    	this.dataSourceForm.dataGroupId = ''
            this.dataSourceForm.dataGroupName = ''
	    	this.pagination1.currentPage = 1
            this.searchDataList()
	    },
        formatter (row, column) { // 状态信息中表格展开项的code转为name
            switch (column.property) {
            case "isCustom":// 是否自定义数据组
                return row.isCustom == 1 ? this.$t('common.is') : this.$t('common.not')
            default : return row[column.property]; 
            }
	    }
    }
}
</script>
<style lang="less" scoped>
.handleDialog{
	min-width: 1100px;
	 p{
        display: block;
        -webkit-margin-before: 1em;
        -webkit-margin-after: 1em;
        -webkit-margin-start: 0px;
        -webkit-margin-end: 0px;
    }
}
</style>
